<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>成绩管理</title>
    <script src="./jquery.js"></script>
    <!-- 最新版本的 Bootstrap 核心 CSS 文件 -->
    <link rel="stylesheet" href="./bootstrap-3.4.1/dist/css/bootstrap.css" />
    <!-- 最新的 Bootstrap 核心 JavaScript 文件 -->
    <script src="./bootstrap-3.4.1/dist/js/bootstrap.js"></script>
    <script src="./city.js"></script>
  </head>
  <style>
    .con {
      margin: auto;
      margin-top: 30px;
    }
    .se {
      width: 150px;
      float: left;
    }
    .tableclass {
      margin-top: 30px;
    }
    li {
      border: 1px solid #ccc;
      list-style: none;
      width: 100px;
      height: 30px;
      float: left;
      text-align: center;
    }
    th,
    td {
      text-align: center;
    }
    .modal-content {
      width: 900px;
    }
    .c-div {
      width: 900px;
      margin: auto;
    }
    .s-div {
      width: 900px;
      margin: auto;
    }
  </style>
  <body>
    <div class="c-div">
      <h1>学生成绩管理</h1>
      <select class="form-control se" id="classList"></select>
      <select class="form-control se" id="stage">
        <option value="">请选择阶段</option>
        <option value="0">一段</option>
        <option value="1">二段</option>
        <option value="2">三段</option>
        <option value="3">四段</option>
        <option value="4">五段</option>
        <option value="5">六段</option>
        <option value="6">实训毕业段</option>
      </select>
      <!-- Button trigger modal -->
      <button
        type="button"
        class="btn btn-default"
        data-toggle="modal"
        data-target="#saveClassModal"
        id="class-manage"
      >
        班级管理
      </button>

      <!-- Modal -->
      <div
        class="modal fade"
        id="saveClassModal"
        tabindex="-1"
        role="dialog"
        aria-labelledby="myModalLabel"
      >
        <div class="modal-dialog" role="document">
          <div class="modal-content">
            <div class="modal-header">
              <button
                type="button"
                class="close"
                data-dismiss="modal"
                aria-label="Close"
              >
                <span aria-hidden="true">&times;</span>
              </button>
              <h4 class="modal-title" id="myModalLabel">班级列表</h4>
            </div>
            <div class="modal-body">
              <table class="table table-bordered">
                <thead>
                  <tr>
                    <th>班级ID</th>
                    <th>班级名称</th>
                    <th>备注选项</th>
                    <th>添加时间</th>
                    <th>操作管理</th>
                  </tr>
                </thead>
                <tbody id="tbd-class"></tbody>
              </table>
              <button type="button" class="btn btn-default" id="add-class">
                添加班级
              </button>
            </div>
            <div class="modal-footer">
              <button
                type="button"
                class="btn btn-default"
                data-dismiss="modal"
              >
                关闭
              </button>
            </div>
          </div>
        </div>
      </div>
    </div>
    <!-- 学生成绩列表 -->
    <div class="s-div">
      <table class="table table-bordered tableclass">
        <thead>
          <tr>
            <th rowspan="2" style="line-height: 55px">姓名</th>
            <th>第一周</th>
            <th colspan="3">第二周</th>
            <th>第三周</th>
            <th colspan="3">第四周</th>
            <th rowspan="2" style="line-height: 55px">月平均分数</th>
            <th rowspan="2" style="line-height: 55px">末位次数</th>
            <th rowspan="2" style="line-height: 55px">操作</th>
          </tr>
          <tr>
            <th>机试分数</th>
            <th>笔试分数</th>
            <th>机试分数</th>
            <th>平均分数</th>
            <th>机试分数</th>
            <th>笔试分数</th>
            <th>机试分数</th>
            <th>平均分数</th>
          </tr>
        </thead>
        <tbody id="tbd-student"></tbody>
      </table>
      <button
        class="btn btn-default"
        data-toggle="modal"
        data-target="#addStudentModal"
        id="add-student"
      >
        添加学生
      </button>
      <div
        class="modal fade"
        id="addStudentModal"
        tabindex="-1"
        role="dialog"
        aria-labelledby="myModalLabel"
        aria-hidden="true"
      >
        <div class="modal-dialog">
          <div class="modal-content">
            <div class="modal-header">
              <button
                type="button"
                class="close"
                data-dismiss="modal"
                aria-hidden="true"
              >
                &times;
              </button>
              <h4 class="modal-title" id="myModalLabel">添加学生</h4>
            </div>
            <div class="modal-body">
              学生姓名:
              <input
                type="text"
                id="studentName"
                class="form-control"
                style="width: 180px"
              />
              <br />
              请选择班级:
              <select
                class="form-control"
                style="width: 180px"
                name=""
                id="add-se1"
              ></select
              ><br />
            </div>
            <div class="modal-footer">
              <button
                type="button"
                class="btn btn-default"
                data-dismiss="modal"
              >
                关闭
              </button>
              <button type="button" class="btn btn-primary" id="saveStudent">
                确定添加
              </button>
            </div>
          </div>
          <!-- /.modal-content -->
        </div>
        <!-- /.modal -->
      </div>
    </div>
  </body>
  <style>
    .new-class input {
      width: 100%;
      border: none;
      outline: none;
    }
    .suibian {
      width: 100%;
      border: none;
      outline: none;
    }
  </style>
  <script>
    var ID,
      stuGrade = [],
      thisClassId
    $(function () {
      $('#class-manage').click(showClassModal)
      $('#saveClass').click(saveClass)
      $('#add-class').click(addNewClass)
      $('#tbd-class').dblclick(editClass)
      $('#stage,#classList').change(showStudentGrade)
      $('#add-student').click(addStudent)
      $('#saveStudent').click(saveStudent)
      $('#tbd-student').dblclick(editStudent)
      //显示班级列表
      showClassList()
      //显示学生成绩列表
      showStudentGrade()
    })
    //编辑学生成绩
    function editStudent() {
      console.log($(event.target), 123123)
      if ($(event.target).attr('name') != 'action') {
        var index = $(event.target).attr('data-index'),
          n = $(event.target).attr('data-n')
        var strHtml = `<input type="text" style="width:50px" onblur="saveNumer(this, ${index},${n})" value="${$(
          event.target
        ).html()}">`
        $(event.target).html(strHtml)
      }
    }
    //保存学生成绩
    function saveNumer(obj, index, n = -1) {
      var classIndex = stuGrade.findIndex(function (item) {
        return item.classid == thisClassId
      })
      var thisStage = $('#stage').val()
      if (n > -1) {
        stuGrade[classIndex].student[index].grade[thisStage][n] = $(obj).val()
      } else {
        stuGrade[classIndex].student[index].name = $(obj).val()
      }
      setData('stuGrade', stuGrade)
      showStudentGrade()
    }
    //保存添加学生
    function saveStudent() {
      //关闭模态框
      $('#addStudentModal').modal('hide')
      var stuName = $('#studentName').val()
      var classId = $('#add-se1').val()
      if (!stuName || !classId) {
        alert('请填写完整信息')
        return
      }
      var stuObj = {
        name: stuName,
        grade: [
          ['', '', '', '', '', '', '', '', '', ''],
          ['', '', '', '', '', '', '', '', '', ''],
          ['', '', '', '', '', '', '', '', '', ''],
          ['', '', '', '', '', '', '', '', '', ''],
          ['', '', '', '', '', '', '', '', '', ''],
          ['', '', '', '', '', '', '', '', '', ''],
          ['', '', '', '', '', '', '', '', '', ''],
        ],
      }
      var classIndex = stuGrade.findIndex(function (item) {
        return item.classid == classId
      })
      if (!stuGrade[classIndex]) {
        stuGrade.push({
          classid: classId,
          classname: $('#add-se1 option:selected').text(),
          student: [stuObj],
        })
      } else {
        stuGrade[classIndex].student.push(stuObj)
      }
      setData('stuGrade', stuGrade)
      showStudentGrade()
    }
    //添加学生显示班级
    function addStudent() {
      var classList = getData('classList')
      var str = '<option value="">请选择班级</option>'
      for (let i in classList) {
        str += `<option value="${classList[i].id}">${classList[i].className}(${classList[i].markClass})</option>`
      }
      $('#add-se1').html(str)
    }
    var thisClassId = 0
    //显示学生成绩列表
    function showStudentGrade() {
      stuGrade = getData('stuGrade')
      thisClassId = $('#classList').val()
      var thisStage = $('#stage').val()
      var student = getStudentById(thisClassId)
      //首次打开默认显示这个 请选择班级
      if (!thisClassId || !thisStage || student.length < 1) {
        $('#tbd-student').html(`
          <tr>
            <td name='action' rowspan="5" colspan="13" style="height:100px;line-height:100px">请选择班级</td>
          </tr>
        `)
        return
      }

      var html = ''
      for (let i in student) {
        html += `<tr><td data-index="${i}">${student[i].name}</td>`
        for (let j in student[i].grade[thisStage]) {
          html += `<td data-index="${i}" data-n='${j}' >${student[i].grade[thisStage][j]}</td>`
        }
        html += `<td name="action">
                    <button class="btn btn-default" onclick="delStudent(${i})">删除</button>
                </td>
                </tr>`
      }
      $('#tbd-student').html(html)
    }
    //删除学生
    function delStudent(index) {
      stuGrade = getData('stuGrade')
      var classIndex = stuGrade.findIndex(function (item) {
        return item.classid == thisClassId
      })
      stuGrade[classIndex].student.splice(index, 1)
      setData('stuGrade', stuGrade)
      showStudentGrade()
    }
    //通过ID获取学生数据
    function getStudentById(id) {
      var classIndex = stuGrade.findIndex(function (item) {
        return item.classid == id
      })
      if (classIndex > -1) {
        return stuGrade[classIndex].student
      } else {
        return []
      }
    }
    //添加一个班级
    function addNewClass() {
      var strHtml = `<tr class="new-class">
                        <td>ID</td>
                        <td><input type="text" id="newClass" placeholder="请输入班级名称"></td>
                        <td><input type="text" id="markClass" placeholder="备注（可选）"></td>
                        <td>添加时间</td>
                        <td><button class="btn btn-default" onclick="showClassModal()">取消添加</button> <button class="btn btn-default" onclick="saveClass()">确定添加</button></td>
                    </tr>`
      $('#tbd-class').append(strHtml)
    }

    //显示班级列表模态框
    function showClassModal() {
      var classList = getData('classList')
      var html = ''
      for (let i in classList) {
        html += `<tr>
                        <td>${classList[i].id}</td>
                        <td name="classname" data-index="${i}">${classList[i].className}</td>
                        <td name="mark" data-index="${i}">${classList[i].markClass}</td>
                        <td>${classList[i].created_at}</td>
                        <td><button class="btn btn-default" onclick="delClass(${i})">删除</button></td>
                    </tr>`
      }
      $('#tbd-class').html(html)
    }
    //编辑班级
    function editClass() {
      var classList = getData('classList'),
        index

      if ($(event.target).attr('name') == 'classname') {
        index = $(event.target).attr('data-index')
        var html = `<input type="text" onblur="updateClass(this.value,${index},'cname')" placeholder="请输入班级名称" value="${classList[index].className}">`
      }
      if ($(event.target).attr('name') == 'mark') {
        index = $(event.target).attr('data-index')
        var html = `<input type="text" onblur="updateClass(this.value,${index},'mark')" placeholder="备注(可选)" value="${classList[index].markClass}">`
      }
      $(event.target).html(html)
    }
    //更新班级数据
    function updateClass(val, index, type) {
      var classList = getData('classList')
      if (type == 'cname') {
        classList[index].className = val
      } else {
        classList[index].markClass = val
      }
      setData('classList', classList)
      showClassModal()
      showClassList()
    }
    //删除班级
    function delClass(index) {
      if (confirm('确定删除吗？')) {
        var classList = getData('classList')
        classList.splice(index, 1)
        setData('classList', classList)
        showClassList()
        showClassModal()
      }
    }
    //显示班级列表
    function showClassList() {
      var classList = getData('classList')
      var str = '<option value="">请选择班级</option>'
      for (let i in classList) {
        str += `<option value="${classList[i].id}">${classList[i].className}(${classList[i].markClass})</option>`
      }
      $('#classList').html(str)
    }
    //添加班级
    function saveClass() {
      var newClass = $('#newClass').val()
      var markClass = $('#markClass').val()
      if (!newClass) {
        alert('请输入班级名称')
        return
      }
      var id = getId()
      var created_at = getNowTime()
      var dataObj = {
        id: id,
        className: newClass,
        markClass: markClass,
        created_at: created_at,
      }
      addData('classList', dataObj)
      showClassList()
      showClassModal()
      //   $('#saveClassModal').modal('hide')
    }

    //获取本地数据
    function getData(key) {
      return localStorage.getItem(key)
        ? JSON.parse(localStorage.getItem(key))
        : []
    }
    //删除本地数据
    function delData(key, index) {
      let data = getData(key)
      data.splice(index, 1)
      setData(key, data)
    }
    //设置更新本地数据
    function setData(key, data) {
      localStorage.setItem(key, JSON.stringify(data))
    }
    //追加本地数据
    function addData(key, data = {}) {
      let localData = getData(key)
      localData.unshift(data)
      setData(key, localData)
    }
    //生成自增ID
    function getId() {
      ID = getData('id') ? Number(getData('id')) : 0
      ID++
      setData('id', ID)
      return ID
    }
    //获取当前时间
    function getNowTime() {
      var date = new Date()
      var year = date.getFullYear()
      var month = date.getMonth() + 1
      var day = date.getDate()
      var hour = date.getHours()
      var minute = date.getMinutes()
      var second = date.getSeconds()
      return (
        year +
        '-' +
        month +
        '-' +
        day +
        ' ' +
        hour +
        ':' +
        minute +
        ':' +
        second
      )
    }
  </script>
</html>
